package hierarchydisplay;

import java.awt.Graphics;
import java.awt.Point;

import shapes.Rectangle;
import shapes.TextShape;
import util.TextDraw;

public class Node implements INode {
	/**
	 * Base node
	 */

	protected HierarchyDisplay hierarchyDisplay;
	
	protected String text = "Noname";
	
	/* State variables */
	protected Rectangle shape = null;

	public Node(HierarchyDisplay hd) {
		this.hierarchyDisplay = hd;
		shape = new Rectangle(0,0,10,10);
	}

	/* Get current shape for display */
	public TextShape getShape() {
		return shape;
	}

	/* Draw node */
	public void draw(Graphics g) {
		shape.draw(g);
	}

	/* Test if text fits in the shape */
	public boolean textFits(String text) {
		return calcTextWidth(text) < shape.getWidth();
	}

	/* Generate node layout */
	public void calculateLayout(int y, int stepY, int leftX, int rightX) {
		positionNode(new Point((rightX + leftX) / 2, y), rightX - leftX - 10);
	}

	/* update text */
	public void textChanged() {
		shape.setText(getText());
	}

	/* Position node at given place */
	protected void positionNode(Point pt, int maxWidth) {
		int width = maxWidth > 150 ? 150 : maxWidth;
		adjustShape(pt, width);
		shape.setText(getText());
	}

	/* Adjust shape for given center point and width */
	protected void adjustShape(Point center, int width) {
		shape.setPoints(center.x - width / 2, center.y - 20, center.x + width
				/ 2, center.y + 20);
	}

	/* Calculate text width */
	protected int calcTextWidth(String text) {
		return TextDraw.calcTextWidth(hierarchyDisplay.getGraphics(), text) + 10;
	}

	/* Calculate the total number of leaves under the node (needed for layout) */
	public int getNumLeaves() {
		return 1;
	}

	public void setText(String text) {
		this.text = text;
	}
	
	public String getText() {
		return text;
	}
}
